// 导入数据库API
const db = require('../../config/db');
// 导入加密/解密文件
const aes2 = require('../../utils/aes2');
// 导入jwt token工具
const JwtUtil = require('../../utils/jwt');
// 封装注册接口
const register = (admin_id, admin_acc, admin_pwd, admin_name, admin_create_time) => {
    return new Promise((resolve, reject) => {
        let admin_check_sql = `select * from db_admin where admin_acc = "${admin_acc}"`
        db.query(admin_check_sql, (error, result) => {
            if (error) {
                reject({
                    code: -1,
                    msg: '查询管理员异常。'
                })
            } else {
                // result: 数组
                if (result.length == 0) {
                    let pwd = aes2.aesEncrypt(admin_pwd)//加密
                    let role = 'admin';
                    let admin_insert_sql = `insert into db_admin(admin_id,admin_acc,admin_pwd,admin_name,admin_create_time,role) values("${admin_id}","${admin_acc}","${pwd}","${admin_name}","${admin_create_time}","${role}")`;
                    db.query(admin_insert_sql, (err, rows) => {
                        if (err) {
                            reject({
                                code: -1,
                                msg: `管理员${admin_acc}注册失败。`,
                                err
                            })
                        } else {
                            resolve({
                                code: 200,
                                msg: '管理员注册成功。',
                                admin_name
                            })
                        }
                    })
                } else {
                    resolve({
                        code: 201,
                        msg: '该账号已经存在。'
                    })
                }
            }
        })
    })
}

// 封装管理员登录接口
// 设置管理员登录的有效时间
// 把管理员的admin_id生产临时的随机字符串(token)
// token: 临时身份（令牌）
const login = (admin_acc, admin_pwd) => {
    return new Promise((resolve, reject) => {
        // 查询管理员表sql语句
        let admin_check_sql = `select * from db_admin where admin_acc="${admin_acc}"`;
        db.query(admin_check_sql, (err, rows) => {
            if (err) {
                resolve({
                    code: -1,
                    msg: '账号或密码错误。'
                })
            } else {
                if (rows.length == 1) {
                    // 匹配密码
                    // 参数1：前端提交的密码，参数2：数据库的密码
                    // console.log('7.0', aes2.aesDecrypt(admin_pwd, rows[0]['admin_pwd']));
                    if (aes2.aesDecrypt(admin_pwd, rows[0]['admin_pwd'])) {
                        let [{ admin_id, admin_name, admin_acc, admin_phone }] = rows;
                        // 将管理员id传入并生成token
                        let jwt = new JwtUtil(admin_id);
                        // 获取token
                        let token = jwt.generateToken();
                        // 定义管理员对象
                        let user = {
                            code: 200,
                            msg: `管理员${admin_acc},登录成功。`,
                            token,
                            admin_name,
                            admin_acc,
                        }
                        // 将 token 等信息反馈给客户端
                        resolve(user);
                    } else {
                        resolve({
                            code: -1,
                            msg: '账号或密码错误1'
                        })
                    }
                }
                else if (rows.length == 0) {
                    resolve({
                        code: -1,
                        msg: '账号不存在。'
                    })
                }
                else {
                    resolve({
                        code: 500,
                        msg: '系统异常。'
                    })
                }
            }
        })
    })
}

// 操作数据库的业务
module.exports = {
    // 示例：
    test() {
        return new Promise((resolve, reject) => { })
    },
    // 注册接口
    register(admin_id, admin_acc, admin_pwd, admin_name, admin_create_time) {
        // To do ....
        return register(admin_id, admin_acc, admin_pwd, admin_name, admin_create_time);
    },
    // 登录接口
    login(admin_acc, admin_pwd) {
        // To do ....
        return login(admin_acc, admin_pwd);
    },
    // 修改资料
    modify(admin_id, admin_name, admin_pwd) {
        return new Promise((resolve, reject) => {
            let modify_info_sql = ''
            if (admin_name.length != 0) {
                modify_info_sql = `update db_admin set admin_name= "${admin_name}" where  admin_id= "${admin_id}"`;
                // console.log('1.0', {modify_info_sql})
                if (admin_pwd.length != 0) {
                    modify_info_sql = `update db_admin set admin_name= "${admin_name}",admin_pwd="${admin_pwd}" where  admin_id= "${admin_id}"`;
                    // console.log('2.0', { modify_info_sql })
                }
            }
            db.query(modify_info_sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "修改管理员资料失败。",
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "修改管理员资料成功。"
                    })
                }
            })
        })
    },

    // 删除管理员信息
    remove(admin_id) {
        return new Promise((resolve, reject) => {
            let sql = `delete from  db_admin where admin_id = "${admin_id}"`
            db.query(sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "删除管理员失败。",
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "删除管理员成功。"
                    })
                }
            })
        })
    },

    // 获取管理员信息
    get_userInfo(admin_id) {
        // console.log('333',{admin_id})
        return new Promise((resolve, reject) => {
            let sql = `select admin_name,admin_acc from db_admin where admin_id = "${admin_id}"`;
            db.query(sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: '获取管理员信息失败。'
                    })
                } else {
                    reject({
                        code: 200,
                        msg: '获取管理员信息成功。',
                        data: rows
                    })
                }
            })
        })
    },

    // 删除管理员信息(管理员删除用户)
    delete(user_id) {
        return new Promise((resolve, reject) => {
            let sql = `delete from  db_user where user_id = "${user_id}"`
            db.query(sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "删除用户失败。",
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "删除用户成功。",
                        user_id
                    })
                }
            })
        })
    },

    // 用户列表
    list(page_num, page_size) {
        return new Promise((resolve, reject) => {
            let startIndex = (page_num - 1) * page_size;
            let len = page_size;
            let sql = "select * from db_user limit " + startIndex + "," + len + "";
            db.query(sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '获取用户列表失败。',
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "获取用户列表成功。",
                        result: rows,
                        page: {
                            page_num: page_num,
                            page_size: page_size,
                        }
                    })
                }
            })
        })

    },

    // 用户详情
    detail(user_id) {
        return new Promise((resolve, reject) => {
            let sql = `select * from db_user where user_id="${user_id}"`;
            db.query(sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询用户列表失败。',
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "查询用户详情成功。",
                        result: rows
                    })
                }
            })
        })
    },

    // 搜索用户
    // 参数：keyword
    search(keyword) {
        return new Promise((resolve, reject) => {
            let sql = "select * from db_user where user_name LIKE CONCAT('%" + keyword + "%') or user_acc LIKE CONCAT('%" + keyword + "%')";
            db.query(sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询用户信息失败。',
                        err
                    })
                } else {
                    if (rows.length == 0) {
                        resolve({
                            code: -1,
                            msg: '没有该关键字匹配的用户信息。'
                        })
                    } else {
                        resolve({
                            code: 200,
                            msg: '查询用户信息成功。',
                            result: rows
                        })
                    }
                }
            })
        })
    },

    // 统计用户数量
    total() {
        return new Promise((resolve, reject) => {
            db.query('select count(*) as total from db_user', (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '统计用户数量失败。',
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "获取用户数量成功。",
                        total: rows[0]['total']
                    })
                }
            })

        })
    },
}